package com.jt.chapter02.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.chapter02.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiang tao
 * @date 2022/1/7
 * @description:
 **/
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    SessionRegistry sessionRegistry;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("登录不支持非post提交方式");
        }
//        如果传输格式是application/json就执行自己的逻辑，否则就执行UsernamePasswordAuthenticationFilter的逻辑
        if(request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)){
            Map<String, String> loginData = new HashMap<>();
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());
            username = username == null ? "" : username.trim();
            password = password == null ? "" : password;
            System.out.println(username+"------"+password);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,password);
            setDetails(request,usernamePasswordAuthenticationToken);
            User user = new User();
            user.setUsername(username);
            return this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);

        }else{
//            执行UsernamePasswordAuthenticationFilter的逻辑
            return super.attemptAuthentication(request,response);
        }


    }
}
